/*
	Anonymous Image Board Image Downloader - program for downloading pictures from AIB
	Copyright (C) 2011-2012 Metallhead <Metallhead@megabox.ru>

	HomePage:    http://code.google.com/p/aibid/

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "xmleditor.h"
#include "ui_xmleditor.h"
#include <QDebug>
#include <QMessageBox>

XmlEditor::XmlEditor(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::XmlEditor)
{
    ui->setupUi(this);
	changeEditedState(false);
	hocusPocus = false;
	ui->tableWidget->setColumnCount(2);
	//set up appearence
	QHeaderView * header = new QHeaderView(Qt::Horizontal,ui->tableWidget);
	header->setResizeMode(QHeaderView::ResizeToContents);
	ui->tableWidget->setHorizontalHeader(header);
	QStringList headers;
	headers<< tr("Detector") << tr("Site name");
	ui->tableWidget->setHorizontalHeaderLabels(headers);
	ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);

	//search xml files in folder
	Common::fillParsersCombobox(ui->files);
	//read current xml file to localDetectors
	QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
	readLocalDetectors(settings.value("settings/parser").toString());

	connect(ui->buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyButtonClicked()));
}

XmlEditor::~XmlEditor()
{
    delete ui;
}

void XmlEditor::on_moveHigher_clicked()
{
	moveRow(true);
}

void XmlEditor::on_tableWidget_currentCellChanged(int currentRow, int, int, int)
{
	ui->moveHigher->setEnabled(currentRow);
	ui->moveLower->setEnabled((currentRow!=ui->tableWidget->rowCount()-1) && (ui->files->currentText()!="parsers.xml"));
	ui->detector->setText(ui->tableWidget->item(currentRow,0)->text());
	ui->siteName->setChecked(ui->tableWidget->item(currentRow,1)->text()=="+");

}

void XmlEditor::on_moveLower_clicked()
{
	moveRow(false);
}

void XmlEditor::moveRow(bool up)
{
	changeEditedState(true);
	int direction = up ? -1 : 1;
	int row = ui->tableWidget->currentIndex().row();
	int column = ui->tableWidget->currentIndex().column();
	for(int i=0;i<2;i++)
	{
		QString temp = ui->tableWidget->item(row,i)->text();
		QTableWidgetItem * anotherRow = ui->tableWidget->item(row, i);
		anotherRow->setText(ui->tableWidget->item(row+direction,i)->text());
		QTableWidgetItem * newRow = ui->tableWidget->item(row+direction,i);
		newRow->setText(temp);
	}

	ui->tableWidget->setCurrentItem(ui->tableWidget->item(row+direction,column));
	ui->tableWidget->resizeColumnsToContents();
}

void XmlEditor::on_detector_textEdited(QString)
{
	QTableWidgetItem * item = ui->tableWidget->item(ui->tableWidget->currentIndex().row(),0);
	item->setText(ui->detector->text());
	changeEditedState(true);
}

void XmlEditor::on_siteName_clicked()
{
	QTableWidgetItem * item = ui->tableWidget->item(ui->tableWidget->currentIndex().row(),1);
	item->setText(ui->siteName->isChecked() ? "+" : "-");
	changeEditedState(true);
}

void XmlEditor::on_addOver_clicked()
{
	insertRow(ui->tableWidget->currentIndex().row());
}

void XmlEditor::on_addUnder_clicked()
{
	insertRow(ui->tableWidget->currentIndex().row()+1);
}

void XmlEditor::insertRow(int row)
{
	changeEditedState(true);
	ui->tableWidget->insertRow(row);
	{
		QTableWidgetItem * item = new QTableWidgetItem("");
		ui->tableWidget->setItem(row,0,item);
	}
	{
		QTableWidgetItem * item = new QTableWidgetItem("-");
		ui->tableWidget->setItem(row,1,item);
	}
}

void XmlEditor::on_deleteDetector_clicked()
{
	changeEditedState(true);
	if(ui->tableWidget->currentRow()!=-1)
		ui->tableWidget->removeRow(ui->tableWidget->currentIndex().row());
}

void XmlEditor::on_buttonBox_accepted()
{
	saveAll();
	this->close();
}

void XmlEditor::applyButtonClicked()
{
	saveAll();
}

void XmlEditor::saveAll()
{
	localDetectors.clear();
	for(int i=0;i<ui->tableWidget->rowCount();i++)
	{
		detectorStruct detector;
		detector.detector = ui->tableWidget->item(i,0)->text();
		detector.siteName = ui->tableWidget->item(i,1)->text()=="+";
		localDetectors.append(detector);
	}
	QFile file(Common::filePlace(ui->files->itemText(currentFile)));
	file.open(QIODevice::WriteOnly);
	QXmlStreamWriter stream(&file);
	stream.setAutoFormatting(true);
	stream.writeStartDocument();
	stream.writeStartElement("detectors");
	foreach(detectorStruct detector, localDetectors)
	{
		stream.writeStartElement("detector");
		stream.writeTextElement("text", detector.detector);
		stream.writeTextElement("siteName", detector.siteName ? "1" : "0");
		stream.writeEndElement();
	}
	stream.writeEndElement();
	stream.writeEndDocument();
	file.close();
	QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
	if(ui->files->itemText(currentFile) == settings.value("settings/parser").toString())
		detectors = Common::readDetectors(settings.value("settings/parser").toString());
	changeEditedState(false);
	ui->status->setText(tr("File saved"));
}

void XmlEditor::readLocalDetectors(QString fileName)
{
	localDetectors = Common::readDetectors(fileName);
	//fill table
	ui->tableWidget->setRowCount(localDetectors.count());
	for(int i=0;i<ui->tableWidget->rowCount();i++)
	{
		ui->tableWidget->setItem(i,0,new QTableWidgetItem(localDetectors.at(i).detector));
		QString siteName = localDetectors.at(i).siteName ? "+" : "-";
		ui->tableWidget->setItem(i,1,new QTableWidgetItem(siteName));
	}
	currentFile = ui->files->findText(fileName);
	ui->status->setText(tr("File opened"));
	if(ui->tableWidget->rowCount()!=0)
	{
		ui->tableWidget->setCurrentCell(0,0);
		on_tableWidget_currentCellChanged(0,0,0,0);
	}
}


void XmlEditor::on_files_currentIndexChanged(const QString &arg1)
{
	if(hocusPocus)
	{
		hocusPocus = false;
		return;
	}
	if(edited)
	{	
		QMessageBox box;
		box.setText(tr("This file was edited. Do you want to save changes?"));
		box.setWindowTitle(tr("Warning"));
		box.setStandardButtons(QMessageBox::Cancel|QMessageBox::No|QMessageBox::Yes);
		int res = box.exec();
		switch(res)
		{
		case QMessageBox::Cancel:
		{
			hocusPocus = true;
			ui->files->setCurrentIndex(currentFile);
			return;
		}
		case QMessageBox::No:
			changeEditedState(false);
			break;
		case QMessageBox::Yes:
			saveAll();
			break;
		}
	}
	readLocalDetectors(arg1);
	checkForbiddenName();

}

void XmlEditor::changeEditedState(bool edit)
{
	edited = edit;
	if(edit)
		ui->status->setText(tr("File edited"));
}

void XmlEditor::on_addFile_clicked()
{
	if(edited)
	{
		QMessageBox box;
		box.setWindowTitle(tr("Warning"));
		box.setText(tr("This file was edited. Do you want to save changes?"));
		box.setStandardButtons(QMessageBox::Cancel|QMessageBox::No|QMessageBox::Yes);
		int res = box.exec();
		switch(res)
		{
		case QMessageBox::Cancel:
			return;
		case QMessageBox::No:
			changeEditedState(false);
			break;
		case QMessageBox::Yes:
			saveAll();
			break;
		}
	}
	QString fileName = "";
	while(fileName.isEmpty())
		fileName = QInputDialog::getText(this, tr("Please, enter new file name"), tr("File name:"));
	if(!fileName.endsWith(".xml"))
		fileName += ".xml";
	Common::createEmptyParserFile(fileName);
	hocusPocus = true;
	Common::fillParsersCombobox(ui->files);
	int newIndex = ui->files->findText(fileName);
	ui->files->setCurrentIndex(newIndex);
}

void XmlEditor::on_deleteFile_clicked()
{
	QFile file(ui->files->currentText());
	file.remove();
	ui->files->removeItem(ui->files->currentIndex());
}

void XmlEditor::checkForbiddenName()
{
	bool enabled = ui->files->currentText() != "parsers.xml";
	ui->tableWidget->setEnabled(enabled);
	ui->siteName->setEnabled(enabled);
	ui->addOver->setEnabled(enabled);
	ui->addUnder->setEnabled(enabled);
	ui->moveHigher->setEnabled(enabled);
	ui->moveLower->setEnabled(enabled);
	ui->deleteDetector->setEnabled(enabled);
	ui->detector->setEnabled(enabled);
	ui->deleteFile->setEnabled(enabled);
}
